﻿using System;
using System.Data.Entity.Validation;
using System.Linq;
using EntityFramework.Extensions;
using Wabo.Dal.Interface;

namespace Wabo.Dal.Repository
{
    
    public class WaboEFLogRepository:EFBaseRepository,ILogRepository
    {
        
        public WaboLog Log(User usr, LogOperation operation, string moduleName,string actionName,string description="")
        {
            try
            {
                var logEntry = new WaboLog
                    {
                        log_operation_type = (int) operation,
                        user_id = usr.id,
                        description = description,
                        module = moduleName,
                        action = actionName,
                        date = DateTime.Now
                    };
                Context.Logs.Add(logEntry);
                Context.SaveChanges();
                return logEntry;
            }
            catch (DbEntityValidationException ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }


        public IQueryable<WaboLog> Logs
        {
            get 
            { 
                return Context.Logs.OrderByDescending(lg => lg.date); 
            }
        }


        public void Remove(int days)
        {
            try
            {
                DateTime lastDay = DateTime.Now.AddDays( 0-days );
                Context.Logs.Delete( l => l.date < lastDay);
                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }

        public void RemoveAll()
        {
            try
            {
                Context.Logs.Delete(l => true);
                Context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }
    }
}
